package com.sky.controller.admin;

import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("admin/common")
public class CommonController {

    //工具类
    @Autowired
    private AliOssUtil aliOssUtil;

//    文件上传
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws IOException {
        try {
            String extension=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            //防止文件名一样时冲突
            UUID uuid = UUID.randomUUID();
            String uuidStr = uuid.toString();
            String fileName = uuidStr+extension;
            // 上传文件到OSS
            String fileUrl = aliOssUtil.upload(file.getBytes(), fileName);
            // 返回上传结果
            return Result.success(fileUrl);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        return Result.error("文件上传失败");
    }
}
